package DataStructrue.tree;

import java.util.HashMap;
import java.util.Map;

//动态线段树
public class DynamicSegTree {
    private Map<Integer, Integer> tree;//线段树,表示某节点的值
    private Map<Integer, Integer> lazy;//懒标记
    private int begin;//起始点
    private int end;//终止点
    public DynamicSegTree() {
        tree = new HashMap<>();
        lazy = new HashMap<>();
        begin=1;
        end= (int)1e9;
    }
    //区间修改(增加)
    public void update(int l,int r,int val){
        if(l>r) return;
        update(l,r,begin,end,1,val);
    }
    private void update( int l, int r,int curl, int curr, int node,int val) {
        //区间无交集
        if (curl>r||curr<l)
            return;
        //当前区间在目标区间内
        if (l<=curl&&curr<=r) {
            tree.put(node, tree.getOrDefault(node, 0) +(curr-curl+1)*val);//更新当前节点
            if(curl<curr) lazy.put(node, lazy.getOrDefault(node, 0) + val);
        } else {
            //当前区间与目标区间存在交集
            int mid = (curl + curr) >> 1;
            if(lazy.getOrDefault(node,0)!=0)
                pushDown(node,curr-curl+1);
            //更新子区间
            update( l, r, curl, mid,2 * node,val);
            update(l, r, mid+1, curr, 2 * node + 1,val);
            pushUp(node);//更新当前节点
        }
    }
    private void pushUp(int node){
        tree.put(node, tree.getOrDefault(2 * node, 0)+tree.getOrDefault(2 * node + 1, 0));
    }
    //将标记向下一层传递
    private void pushDown(int node,int len){
        int _lazy=lazy.get(node);
        lazy.put(node*2,lazy.getOrDefault(node*2,0)+_lazy);
        lazy.put(node*2+1,lazy.getOrDefault(node*2+1,0)+_lazy);
        tree.put(node*2,tree.getOrDefault(node*2,0)+(len-len/2)*_lazy);
        tree.put(node*2+1,tree.getOrDefault(node*2+1,0)+len/2*_lazy);
        lazy.put(node,0);
    }
    //区间查询
    public int query(int l,int r){
        if(l>r) return -1;
        return query(l,r,begin,end,1);
    }
    private int query(int l,int r,int curl,int curr,int node){
        //不在目标区间
        if(curl>r||curr<l)
            return 0;
        //在目标区间
        if(l<=curl&&curr<=r)
            return tree.getOrDefault(node,0);
        //部分有交集,分割区间处理
        int mid=(curl+curr)>>1;
        if(lazy.getOrDefault(node,0)!=0)
            pushDown(node,curr-curl+1);
        return  query(l,r,curl,mid,node*2)+query(l,r,mid+1,curr,node*2+1);
    }



}
